package edu.luc.concordia;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.ListModel;

import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.EventListenerList;

import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Vector;

/**
 * Copyright 2008 Project Concordia
 * <p>
 * This file is part of RetailReturnSystem.
 * <p>
 * RetailReturnSystem is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 * <p>
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * <p>
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <a
 * href="http://www.gnu.org/licenses/">http://www.gnu.org/licenses/</a>.
 * <hr>
 * This is Main Class of System. It scans Product Code and Quantity. It also
 * shows Options for System Shut Down and Receipt. It includes GUI for last scan
 * items.
 * 
 * @author Rashmi Pandey
 * @version 2.0 NOV-21-2008
 * 
 */
public class SystemMain extends JPanel implements ActionListener,
		PropertyChangeListener {
	// All Controls Declaration
	private JTextField scanCodeField;
	private JTextField quantityField;
	private JTextField memberField;
	private JTextField lastItemField;
	private JTextField totalField;

	private JButton okButton;

	private JRadioButton receiptButton;
	private JRadioButton reportButton;
	private JRadioButton returnButton;
	private JRadioButton shutDownButton;
	private JButton cancelButton;
	private JButton doneButton;

	private JLabel scanCodeLabel;
	private JLabel quantityLabel;
	private JLabel memberLabel;
	private JLabel lastItemLabel;
	private JLabel totalLabel;
	private JLabel transactionLabel;

	private JList transactionList;
	private JScrollPane transactionScroll;
	private JPanel panel1;

	// Declare and Initialize Listeners
	private EventListenerList listener = new EventListenerList();
	private ActionListener forwardListener = new ActionListener() {
		@Override
		public void actionPerformed(ActionEvent e) {
			Object[] currentListeners = listener.getListenerList();

			for (int i = currentListeners.length - 2; i >= 0; i -= 2) {
				if (currentListeners[i] == ActionListener.class) {
					((ActionListener) currentListeners[i + 1])
							.actionPerformed(e);
				}
			}
		}

	};

	public void addActionListener(ActionListener l) {
		listener.add(ActionListener.class, l);
	}

	// Empty Constructor
	public SystemMain() {

	}

	public SystemMain(JFrame frame) {

		this.setLayout(new BorderLayout());
		this.setLayout(new GridBagLayout());
		this.setName("Retail");
		panel1 = new JPanel();
		panel1.setLayout(new FlowLayout(FlowLayout.LEFT));

		// Member ID Label
		memberLabel = new JLabel("Member ID : ");
		add(memberLabel, getConstraints(0, 0, 1, 1, GridBagConstraints.EAST));

		// Member ID File name text field
		memberField = new JTextField(10);
		add(memberField, getConstraints(1, 0, 1, 1, GridBagConstraints.WEST));
		memberField.setEditable(true);
		memberField.setFocusable(true);

		// Scan item
		scanCodeLabel = new JLabel("Product Code :");
		add(scanCodeLabel, getConstraints(0, 1, 1, 1, GridBagConstraints.EAST));

		// File name text field
		scanCodeField = new JTextField(10);
		add(scanCodeField, getConstraints(1, 1, 1, 1, GridBagConstraints.WEST));
		scanCodeField.setEditable(true);
		scanCodeField.setFocusable(true);

		// Quantity Label
		quantityLabel = new JLabel("Quantity :");
		add(quantityLabel, getConstraints(2, 1, 1, 1, GridBagConstraints.EAST));

		// File name text field
		quantityField = new JTextField(10);
		add(quantityField, getConstraints(3, 1, 1, 1, GridBagConstraints.WEST));
		quantityField.setEditable(true);
		quantityField.setFocusable(true);

		lastItemLabel = new JLabel("Last Item :");
		add(lastItemLabel, getConstraints(0, 4, 1, 1, GridBagConstraints.EAST));

		// File name text field
		lastItemField = new JTextField(15);
		lastItemField.setEditable(false);
		lastItemField.setFocusable(true);
		add(lastItemField, getConstraints(1, 4, 1, 1, GridBagConstraints.WEST));

		// Transaction scroll down
		transactionLabel = new JLabel("Transaction");
		add(transactionLabel, getConstraints(0, 5, 1, 1,
				GridBagConstraints.EAST));
		transactionList = new JList();
		transactionList.setVisible(true);

		transactionScroll = new JScrollPane(transactionList,
				ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
				ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		add(transactionScroll, getConstraints(1, 5, 2, 2,
				GridBagConstraints.EAST));
		transactionScroll.setVisible(true);

		// Total Label
		totalLabel = new JLabel("Total :");
		add(totalLabel, getConstraints(0, 7, 1, 1, GridBagConstraints.EAST));

		// File name text field
		totalField = new JTextField(10);
		totalField.setEditable(false);
		totalField.setFocusable(true);
		add(totalField, getConstraints(1, 7, 1, 1, GridBagConstraints.WEST));

		// Done Button
		doneButton = new JButton("Done");
		doneButton.setActionCommand(ActionConstants.PRINT_RECEIPT);
		doneButton.addActionListener(forwardListener);
		add(doneButton, getConstraints(1, 9, 2, 1, GridBagConstraints.CENTER));

		// OK Button
		okButton = new JButton("OK");

		// okButton.addActionListener(this);
		add(okButton, getConstraints(1, 2, 1, 1, GridBagConstraints.CENTER));

		// okButton.addActionListener(forwardListener);
		okButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String quantity = quantityField.getText();
				int scancode;
				try {
					scancode = Integer.parseInt(quantity);
					if (scancode < 1) {
						scancode = 1;
					}
				} catch (Exception exc) {
					scancode = 1;
				}
				ActionEvent scanevent = new ActionEvent(scanCodeField,
						scancode, ActionConstants.SCAN_ITEM);
				forwardListener.actionPerformed(scanevent);
			}
		});

		// Cancel Button
		cancelButton = new JButton("Cancel");
		cancelButton.addActionListener(this);
		add(cancelButton, getConstraints(2, 2, 1, 1, GridBagConstraints.CENTER));

		// Receipt Button
		receiptButton = new JRadioButton("Receipt");
		receiptButton.addActionListener(this);
		add(receiptButton, getConstraints(0, 3, 1, 1, GridBagConstraints.EAST));

		// changes made for cycle 2
		// Report Button
		reportButton = new JRadioButton("Report");
		reportButton.addActionListener(this);
		add(reportButton, getConstraints(1, 3, 1, 1, GridBagConstraints.WEST));

		// changes made for cycle 2
		// Return Button
		returnButton = new JRadioButton("Return");
		returnButton.addActionListener(this);
		add(returnButton, getConstraints(2, 3, 1, 1, GridBagConstraints.NORTH));

		// ShutDown Button
		shutDownButton = new JRadioButton("Shut Down");
		shutDownButton.addActionListener(this);
		add(shutDownButton, getConstraints(3, 3, 1, 1,
				GridBagConstraints.SOUTHWEST));

	}

	public void actionPerformed(ActionEvent e) {
		Object source = e.getSource();
		if (source == okButton) {
			String scanCode = scanCodeField.getText();
			String quantity = quantityField.getText();
			lastItemField.setText(scanCode);
			totalField.setText(quantity);
		} else if (source == receiptButton) {
			ActionListener currentListener = (ActionListener) (listener
					.getListenerList()[0]);
			JFrame frame = new Display(
					"Retail CheckOut and Return System         Version 2.0 - Team Concordia",
					PanelGenerator.RECEIPT_PANEL, currentListener);
			frame.setVisible(true);
		} // Pass the product scan code into lower pane
		else if (source == reportButton) {
			ActionListener currentListener = (ActionListener) (listener
					.getListenerList()[0]);
			JFrame frame = new Display(
					"Retail CheckOut and Return System         Version 2.0 - Team Concordia",
					PanelGenerator.REPORT_PANEL, currentListener);
			frame.setVisible(true);
		} else if (source == returnButton) {
			// generate the return file
		} else if (source == shutDownButton) {
			ActionListener currentListener = (ActionListener) (listener
					.getListenerList()[0]);
			JFrame frame = new Display(
					"Retail CheckOut and Return System   Version 2.0 - Team Concordia",
					PanelGenerator.SYSTEM_SHUTDOWN_PANEL, currentListener);
			frame.setVisible(true);
		} // Open System ShutDown Window
		else if (source == cancelButton) {
			scanCodeField.setText("");
			quantityField.setText("");

		} // Remove item from the list
		else if (source == doneButton) {
			// ActionListener currentListener = (ActionListener)
			// listener.getListenerList()[0];
			// JFrame frame = new
			// Display("Retail CheckOut and Return System         Version 1.0 - Team Concordia",
			// PanelGenerator.RECEIPT_PANEL, currentListener);
			// frame.setVisible(true);
		}// Open Receipt Window
	}

	/**
	 * This function set position of controls in form
	 * 
	 * 
	 * @param gridx
	 *            x position
	 * @param gridy
	 *            y position
	 * @param gridwidth
	 *            width
	 * @param gridheight
	 *            height
	 * @param anchor
	 *            direction in form
	 * @return all values for particular control
	 */
	private GridBagConstraints getConstraints(int gridx, int gridy,
			int gridwidth, int gridheight, int anchor) {
		GridBagConstraints c = new GridBagConstraints();
		c.insets = new Insets(5, 5, 5, 5);
		c.ipadx = 0;
		c.ipady = 0;
		c.gridx = gridx;
		c.gridy = gridy;
		c.gridwidth = gridwidth;
		c.gridheight = gridheight;
		c.anchor = anchor;
		return c;
	}

	@Override
	/*
	 * Receiving Events from Translation
	 */
	public void propertyChange(PropertyChangeEvent e) {
		// okButton.addActionListener(this);
		if (PropertyConstants.PRODUCT_FOUND_C2.equals(e.getPropertyName())) {
			scanCodeField.setBackground(Color.WHITE);

			ArrayList<Product> productList = (ArrayList<Product>) e
					.getOldValue();
			String desc = (String) e.getNewValue();

			ListModel oldList = transactionList.getModel();
			int size = oldList.getSize();
			Vector<Object> newList = new Vector<Object>(size
					+ productList.size());

			for (Product prod : productList) {
				newList.add(new String(desc + " " + prod.getCalculatedPrice()));
			}

			for (int i = 0; i < size; i++) {
				newList.add(oldList.getElementAt(i));
			}
			transactionList.setListData(newList);

			lastItemField.setText(desc);

			String temp = totalField.getText();
			double currentTotal;

			if (temp.length() > 0)
				currentTotal = Double.parseDouble(temp.substring(1, temp
						.length()));
			else
				currentTotal = 0;

			for (Product prod : productList) {
				currentTotal += prod.getCalculatedPrice();
			}
			totalField.setText(String.format("$%.2f", currentTotal));

		} // set values in field to display
		else if (PropertyConstants.PRODUCT_NOT_FOUND
				.equals(e.getPropertyName())) {
			lastItemField.setText("Product not found");
			scanCodeField.setBackground(Color.RED);
		}// Left blank last field
		else if (PropertyConstants.LIMIT_REACHED.equals(e.getPropertyName())){
			lastItemField.setText("Limit for this item reached");
			scanCodeField.setBackground(Color.RED);
		}

	}

}
